/**
* 系统管理 用户管理
*/
<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 搜索筛选 -->
    <el-form :inline="true" :model="formInline" class="user-search">
      <el-form-item label="关键字：">
        <el-input size="small" v-model="formInline.keyword" placeholder="输入搜索关键字"></el-input>
      </el-form-item>
      <el-form-item label="激活状态：">
        <el-select size="small" v-model="formInline.active" placeholder="请选择">
          <el-option label="全部" value=""></el-option>
          <el-option label="激活" value="true"></el-option>
          <el-option label="禁用" value="false"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button size="small" type="primary" icon="el-icon-search" @click="search">搜索</el-button>
        <el-button size="small" type="primary" icon="el-icon-plus" @click="handleEdit()">添加</el-button>
      </el-form-item>
    </el-form>
    <!--列表-->
    <el-table size="small" @selection-change="selectChange" :data="listData" highlight-current-row v-loading="loading"
              border element-loading-text="拼命加载中" style="width: 100%;">
      <el-table-column align="center" prop="id" type="selection" width="50"/>
      <el-table-column align="center" sortable prop="username" label="用户名" width="120"/>
      <el-table-column align="center" sortable prop="realName" label="真实姓名" width="120"/>
      <el-table-column align="center" sortable prop="telephone" label="手机号" width="120"/>
      <el-table-column align="center" sortable prop="active" label="是否激活" width="120"/>
      <el-table-column align="center" sortable prop="avatar" label="头像" min-width="50">
        <template slot-scope="scope">
          <img :src="avatarDomain+scope.row.avatar" width="40" height="40" class="head_pic"/>
          <!--<el-avatar shape="square" :src="scope.row.avatar" width="40" height="40"/>-->
        </template>
      </el-table-column>
      <el-table-column align="center" sortable prop="sex" label="性别" :formatter="sexFormatter" min-width="50"/>
      <el-table-column align="center" sortable prop="birthday" label="出生日期" min-width="120">
        <template slot-scope="scope">
          <div>{{scope.row.birthday|timestampToDate}}</div>
        </template>
      </el-table-column>
      <el-table-column align="center" sortable prop="email" label="电子邮箱" min-width="120"/>
      <el-table-column align="center" sortable prop="createTs" label="注册时间" min-width="120">
        <template slot-scope="scope">
          <div>{{scope.row.createTs|timestampToTime}}</div>
        </template>
      </el-table-column>
      <!--<el-table-column align="center" sortable prop="isLock" label="状态" min-width="50">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.isLock=='N'?nshow:fshow" active-color="#13ce66" inactive-color="#ff4949"
                     @change="editType(scope.$index, scope.row)">
          </el-switch>
        </template>
      </el-table-column>-->
      <el-table-column label="操作" min-width="400">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button size="mini" type="success" @click="resetPassword(scope.$index, scope.row)">重置密码</el-button>
          <el-button size="mini" type="warning" @click="offlineUser(scope.$index, scope.row)">下线</el-button>
          <el-button size="mini" type="info" @click="refreshCache(scope.$index, scope.row)">刷新缓存</el-button>
          <el-button size="mini" type="danger" @click="showBindRole(scope.$index, scope.row)">分配角色</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <Pagination v-bind:child-msg="pageparm" @callFather="callFather"></Pagination>
    <!-- 编辑界面 -->
    <el-dialog :title="title" :visible.sync="editFormVisible" width="30%" @click='closeDialog("edit")'>
      <el-form label-width="80px" ref="editForm" :model="editForm" :rules="rules">
        <el-form-item label="用户名" prop="username">
          <el-input size="small" v-model="editForm.username" auto-complete="off" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="真实姓名" prop="realName">
          <el-input size="small" v-model="editForm.realName" auto-complete="off" placeholder="请输入姓名"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="telephone">
          <el-input size="small" v-model="editForm.telephone" placeholder="请输入手机号"></el-input>
        </el-form-item>
        <el-form-item label="电子邮件" prop="email">
          <el-input size="small" v-model="editForm.email" placeholder="请输入邮箱地址"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio size="small" border v-model="editForm.sex" :label="0">男</el-radio>
          <el-radio size="small" border v-model="editForm.sex" :label="1">女</el-radio>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click='closeDialog("edit")'>取消</el-button>
        <el-button size="small" type="primary" :loading="loading" class="title" @click="submitForm('editForm')">保存
        </el-button>
      </div>
    </el-dialog>
    <!-- 分配角色界面 -->
    <el-dialog title="分配角色" :visible.sync="bindRolesFormVisible" width="30%" @click='closeDialog("bindRoles")'>
      <el-form label-width="80px" ref="bindRolesForm" :model="bindRolesForm">
        <el-form-item label="分配角色">
          <el-select v-model="bindRolesForm.roleIds" multiple ref="roleList" placeholder="请选择">
            <el-option
              v-for="item in rolesData"
              :key="item.id"
              :label="item.name"
              :value="item.id">
              <span style="float: left;color: #8492a6; font-size: 13px">{{item.name}}</span>
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click='closeDialog("edit")'>取消</el-button>
        <el-button size="small" type="primary" :loading="loading" class="title" @click="bindRoles('bindRolesForm')">保存
        </el-button>
      </div>
    </el-dialog>
    <!-- 数据权限 -->
    <!-- <el-dialog title="数据权限" :visible.sync="dataAccessshow" width="30%" @click='closeDialog("perm")'>
       <el-tree ref="tree" default-expand-all="" :data="UserDept" :props="defaultProps" :default-checked-keys="checkmenu"
                node-key="id" show-checkbox>
       </el-tree>
       <div slot="footer" class="dialog-footer">
         <el-button size="small" @click='closeDialog("perm")'>取消</el-button>
         <el-button size="small" type="primary" :loading="loading" class="title" @click="menuPermSave">保存</el-button>
       </div>
     </el-dialog>-->
    <!-- 所属单位 -->
    <!--<el-dialog title="所属单位" :visible.sync="unitAccessshow" width="30%" @click='closeDialog("unit")'>
      <el-tree ref="tree" default-expand-all="" :data="UserDept" :props="defaultProps" @check-change="handleClick"
               :default-checked-keys="checkmenu" node-key="id" show-checkbox check-strictly>
      </el-tree>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click='closeDialog("unit")'>取消</el-button>
        <el-button size="small" type="primary" :loading="loading" class="title" @click="unitPermSave">保存</el-button>
      </div>
    </el-dialog>-->
  </div>
</template>

<script>
  // 导入请求方法
  import {
    bindRoles,
    offline,
    refreshCache,
    resetPwd,
    roleComboList,
    userActive,
    userList,
    userSave
  } from '../../api/userMG'
  import Pagination from '../../components/Pagination'

  export default {
    data() {
      return {
        nshow: true, //switch开启
        fshow: false, //switch关闭
        loading: false, //是显示加载
        title: '添加用户',
        editFormVisible: false, //控制编辑页面显示与隐藏
        bindRolesFormVisible: false,
        dataAccessshow: false, //控制数据权限显示与隐藏
        unitAccessshow: false, //控制所属单位隐藏与显示
        avatarDomain: 'https://test-obs.3dyunzhan.com',
        rolesData: [],
        // 编辑与添加
        editForm: {
          id: '',
          username: '',
          realName: '',
          roleId: '',
          telephone: '',
          email: '',
          sex: ''
        },
        bindRolesForm: {
          userId: '',
          roleIds: []
        },
        // 选择数据
        selectdata: [],
        // rules表单验证
        rules: {
          username: [
            {required: true, message: '请输入用户名', trigger: 'blur'}
          ],
          realName: [
            {required: true, message: '请输入姓名', trigger: 'blur'}
          ],
          roleId: [{required: true, message: '请选择角色', trigger: 'blur'}],
          telephone: [
            {required: true, message: '请输入手机号', trigger: 'blur'},
            {
              pattern: /^1(3\d|47|5((?!4)\d)|7(0|1|[6-8])|8\d)\d{8,8}$/,
              required: true,
              message: '请输入正确的手机号',
              trigger: 'blur'
            }
          ],
          email: [
            {required: true, message: '请输入邮箱', trigger: 'blur'},
            {
              pattern: /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/,
              required: true,
              message: '请输入正确的邮箱',
              trigger: 'blur'
            }
          ],
          sex: [{required: true, message: '请选择性别', trigger: 'blur'}]
        },
        // 重置密码
        resetpsd: {
          userId: ''
        },
        // 用户下线
        offlineData: {
          userId: ''
        },
        // 搜索请求数据参数
        formInline: {
          pageNum: 1,
          pageSize: 10,
          username: '',
          telephone: '',
          active: ''
        },
        //用户数据
        listData: [],
        // 分页参数
        pageparm: {
          currentPage: 1,
          pageSize: 10,
          total: 10
        }
      }
    },
    // 注册组件
    components: {
      Pagination
    },

    /**
     * 数据发生改变
     */
    watch: {},

    /**
     * 创建完毕
     */
    created() {
      this.getData(this.formInline)
    },

    /**
     * 里面的方法只有被调用才会执行
     */
    methods: {
      // 获取数据方法
      getData(parameter) {
        this.loading = true;
        // 获取用户列表
        userList(parameter).then(res => {
          this.loading = false;
          if (res.success === false) {
            this.$message.info(res.message);
          } else {
            this.listData = res.data.list;
            // 分页赋值
            this.pageparm.currentPage = this.formInline.pageNum;
            this.pageparm.pageSize = this.formInline.pageSize;
            this.pageparm.total = res.data.count
          }
        })
      },
      // 分页插件事件
      callFather(parm) {
        this.formInline.pageNum = parm.currentPage;
        this.formInline.pageSize = parm.pageSize;
        this.getData(this.formInline);
      },
      //搜索事件
      search() {
        this.getData(this.formInline);
      },
      // 修改type
      editType: function (index, row) {
        this.loading = true;
        let parm = {
          lock: '',
          userId: '',
          token: localStorage.getItem('Authorization')
        }
        parm.userId = row.userId
        let lock = row.isLock
        if (lock == 'N') {
          parm.lock = 'Y'
        } else {
          parm.lock = 'N'
        }
        // 修改状态
        userActive(parm).then(res => {
          this.loading = false;
          if (res.success === false) {
            this.$message({
              type: 'info',
              message: res.msg
            })
          } else {
            this.$message({
              type: 'success',
              message: '状态修改成功'
            })
            this.getData(this.formInline)
          }
        })
      },
      //显示编辑界面
      handleEdit: function (index, row) {
        this.editFormVisible = true;
        if (row != undefined && row != 'undefined') {
          this.title = '修改用户基本信息';
          this.editForm.id = row.id;
          this.editForm.username = row.username;
          this.editForm.realName = row.realName;
          this.editForm.roleId = row.roleId;
          this.editForm.telephone = row.telephone;
          this.editForm.email = row.email;
          this.editForm.sex = row.sex;
        } else {
          this.title = '添加用户信息';
          this.editForm.id = '';
          this.editForm.username = '';
          this.editForm.realName = '';
          this.editForm.roleId = '';
          this.editForm.telephone = '';
          this.editForm.email = '';
          this.editForm.sex = '';
        }
      },
      // 编辑、添加提交方法
      submitForm(editData) {
        this.$refs[editData].validate(valid => {
          if (valid) {
            // 请求方法
            userSave(this.editForm).then(res => {
              this.editFormVisible = false;
              this.loading = false;
              if (res.success) {
                this.getData(this.formInline);
                this.$message.success(res.message);
              } else {
                this.$message.info(res.message);
              }
            }).catch(err => {
              this.editFormVisible = false;
              this.loading = false;
              this.$message.error('保存失败，请稍后再试！');
            })
          } else {
            return false
          }
        })
      },
      /*      handleClick(data, checked, node) {
              if (checked) {
                this.$refs.tree.setCheckedNodes([])
                this.$refs.tree.setCheckedNodes([data])
                this.unitparm.deptId = data.id
                this.unitparm.deptName = data.name
                //交叉点击节点
              } else {
              }
            },*/
      // 选择复选框事件
      selectChange(val) {
        this.selectdata = val
      },
      // 关闭编辑、增加弹出框
      closeDialog(dialog) {
        if (dialog === 'edit') {
          this.editFormVisible = false
        } else if (dialog === 'bindRoles') {
          this.bindRolesFormVisible = false
        }
      },
      sexFormatter(row, column) {
        const sex = row[column.property];
        if (sex != null) {
          if (sex === 0) {
            return '男'
          } else if (sex === 1) {
            return '女'
          } else {
            return '未知'
          }
        }
      },
      // 重置密码
      resetPassword(index, row) {
        this.resetpsd.userId = row.userId;
        this.$confirm('确定要重置密码吗?', '信息', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          resetPwd(this.resetpsd).then(res => {
            if (res.success) {
              this.$message.success(res.message);
              this.getData(this.formInline)
            } else {
              this.$message.info(res.message);
            }
          }).catch(err => {
            this.loading = false;
            this.$message.error('重置密码失败，请稍后再试！')
          })
        }).catch(() => {
          this.$message.info('取消重置密码！');
        })
      },
      showBindRole: function (index, row) {
        this.bindRolesFormVisible = true;
        this.bindRolesForm.userId = row.id;
        roleComboList().then(res => {
          this.rolesData = res.data;
        }).catch(err => {
          this.loading = false;
          this.$message.error('获取权限失败，请稍后再试！')
        });
      },
      //绑定角色
      bindRoles(editData) {
        this.$refs[editData].validate(valid => {
          if (valid) {
            bindRoles(this.bindRolesForm).then(res => {
              this.bindRolesFormVisible = false;
              this.loading = false;
              if (res.success) {
                this.$message.success(res.message);
              } else {
                this.$message.info(res.message);
              }
            }).catch(err => {
              this.loading = false;
              this.$message.error('获取权限失败，请稍后再试！')
            })
          } else {
            return false;
          }
        });
      },
      //数据格式化
      /*changeArr(data) {
        var pos = {}
        var tree = []
        var i = 0
        while (data.length != 0) {
          if (data[i].pId == 0) {
            tree.push({
              id: data[i].id,
              name: data[i].name,
              pId: data[i].pId,
              open: data[i].open,
              checked: data[i].checked,
              children: []
            })
            pos[data[i].id] = [tree.length - 1]
            data.splice(i, 1)
            i--
          } else {
            var posArr = pos[data[i].pId]
            if (posArr != undefined) {
              var obj = tree[posArr[0]]
              for (var j = 1; j < posArr.length; j++) {
                obj = obj.children[posArr[j]]
              }

              obj.children.push({
                id: data[i].id,
                name: data[i].name,
                pId: data[i].pId,
                open: data[i].open,
                checked: data[i].checked,
                children: []
              })
              pos[data[i].id] = posArr.concat([obj.children.length - 1])
              data.splice(i, 1)
              i--
            }
          }
          i++
          if (i > data.length - 1) {
            i = 0
          }
        }
        return tree
      },*/
      // 菜单权限-保存
      menuPermSave() {
        let parm = {
          userId: this.saveroleId,
          deptIds: ''
        };
        let node = this.$refs.tree.getCheckedNodes();
        let moduleIds = []
        if (node.length != 0) {
          for (let i = 0; i < node.length; i++) {
            moduleIds.push(node[i].id)
          }
          parm.deptIds = JSON.stringify(moduleIds)
        }
        userSave(parm).then(res => {
          if (res.success) {
            this.$message.success(res.message);
            this.dataAccessshow = false;
            this.getData(this.formInline)
          } else {
            this.$message.info(res.message);
          }
        }).catch(err => {
          this.loading = false;
          this.$message.error('权限保存失败，请稍后再试！')
        })
      },
      // 下线用户
      offlineUser(index, row) {
        this.$confirm('确定要让' + row.userName + '用户下线吗?', '信息', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          offline(row.id).then(res => {
            if (res.success) {
              this.$message({
                type: 'success',
                message: '用户' + row.username + '强制下线成功！'
              });
              this.getData(this.formInline)
            } else {
              this.$message.info(res.message);
            }
          }).catch(err => {
            this.loading = false;
            this.$message.error('用户下线失败，请稍后再试！')
          })
        }).catch(() => {
          this.$message.info("已取消");
        })
      },
      // 刷新缓存
      refreshCache(index, row) {
        debugger;
        refreshCache(row.id).then(res => {
          if (res.success) {
            this.$message.success("刷新成功!");
            this.getData(this.formInline)
          } else {
            this.$message.info(res.message);
          }
        }).catch(err => {
          this.loading = false;
          this.$message.error('刷新失败，请稍后再试！')
        })
      }
    }
  }
</script>

<style scoped>
  .user-search {
    margin-top: 20px;
  }

  .userRole {
    width: 100%;
  }
</style>

